<template>
  <div class="lecturer-data">
    <section class="statistics-bread-crumb top-box">
      <BreadCrumb>
        <template #custom>
          <el-scrollbar>
            <div class="statistic-scroll">
              <div class="statistic">
                <template v-for="item in statisticList" :key="item.id">
                  <div
                    class="item inline-flex cross-center"
                    :class="{ active: item.id == currentStat.id }"
                    @click="statClick(item)"
                  >
                    <div class="svg-icon">
                      <img
                        v-if="item.id == 0"
                        class="icon"
                        src="@images/agency/icon/lecturer-total.svg"
                        alt=""
                      />
                      <img
                        v-else
                        class="icon"
                        src="@images/agency/icon/lecturer-user.svg"
                        alt=""
                      />
                    </div>
                    <span class="name"> {{ item.name }} </span>
                  </div>
                </template>
              </div>
            </div>
          </el-scrollbar>
        </template>
      </BreadCrumb>
    </section>
    <div class="content flex cross-stretch">
      <div class="left flex-0">
        <div class="head flex cross-center main-between">
          <div class="title">累计用户数</div>
          <div class="number">{{ statistics.total_users }}</div>
        </div>
        <div class="sub">
          <template v-for="item in statisticsRadius" :key="item.key">
            <div
              class="item flex cross-center"
              :class="{ active: statisticsSel === item.key }"
              @click="statRadiusClick(item)"
            >
              <div class="svg-icon flex-0">
                <img class="icon" :src="item.icon" alt="" />
              </div>
              <div class="title flex-1">{{ item.title }}</div>
              <div class="value flex-0">
                <template v-if="statistics[item.key] === undefined">--</template>
                <template v-else-if="item.rate">
                  {{ formatPercentUnit(statistics[item.key]) }}
                </template>
                <template v-else-if="item.rmb">
                  ￥{{ statistics[item.key] }}
                </template>
                <template v-else>
                  {{ statistics[item.key] }}
                </template>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div
        v-loading="chartLoading"
        class="right flex-1 flex dir-top"
      >
        <div class="head flex cross-center main-between flex-0">
          <div class="title">{{ currentChartInfo.title }}</div>
          <div class="date-sel">
            <div>
              <el-date-picker
                v-model="trendDateRange"
                style="width: 300px;"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="rangeShortcuts"
                @change="timeChange"
              />
            </div>
          </div>
        </div>
        <div class="bar flex-0 flex cross-center">
          <template v-for="item in currentChartInfo.infoList" :key="item.title">
            <div class="lab">
              {{ item.lab }}
            </div>
            <div class="val">
              {{ item.val }}
            </div>
          </template>
        </div>
        <div class="chart-wrap flex-1">
          <KLineChart
            :is-empty="!(yData?.length && yData[0]?.data?.length)"
            width="100%"
            height="100%"
            x-type="date"
            y-type="number"
            :options="{showMarkLine: true}"
            :x-data="xData"
            :y-data="yData"
            :tooltip="tooltip"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import BreadCrumb from '@/components/base-bread-crumb/index.vue';
import { formatPercentUnit, formatPercent, toolGetDataPageRangeShortCuts as rangeShortcuts, toolGetCountInitDateRange } from '@/utils';
import {
  lecFollower,
  lecStatisticsCore,
  lecStatisticsTrend
} from '@/api/crm-agency/ad/lecturer';
import { KLineChart } from '@/components/k-charts';
import lecturerUser1 from '@images/agency/icon/lecturer-user1.svg';
import lecturerRmb from '@images/agency/icon/lecturer-rmb.svg';
import lecturerFile from '@images/agency/icon/lecturer-file.svg';
import lecturerChart from '@images/agency/icon/lecturer-chart.svg';
import lecturerRefresh from '@images/agency/icon/lecturer-refresh.svg';

defineOptions({ name: 'AgencyAdLecturerLecturerData' });
const statisticList = ref([
  {
    id: 0,
    name: '全部'
  }
]);

const currentStat = ref(statisticList.value[0]);
const statClick = (item: {id: number; name: string;}) => {
  currentStat.value = item;
  dataRefresh();
};
const getLecFollower = async() => {
  statisticList.value = [];
  let hasMore = true;
  if (hasMore) {
    const res = await lecFollower();
    const { data, has_more } = res.data;
    hasMore = has_more;
    statisticList.value = statisticList.value.concat(data);
  }
};

const statisticsRadius = ref([
  {
    key: 'new_users',
    title: '今日新增',
    tooltipTitle: '用户新增',
    chartType: 2, // 请求趋势图type
    icon: lecturerUser1
  },
  {
    key: 'gmv',
    title: '今日成交',
    tooltipTitle: '成交金额',
    chartType: 3, // 请求趋势图type
    icon: lecturerRmb,
    rmb: true
  },
  {
    key: 'order',
    title: '今日订单',
    tooltipTitle: '订单数',
    chartType: 4, // 请求趋势图type
    icon: lecturerFile
  },
  {
    key: 'atv',
    title: '今日客单',
    tooltipTitle: '日均客单价',
    chartType: 7, // 请求趋势图type
    icon: lecturerChart,
    rmb: true
  },
  {
    key: 'change_ratio',
    title: '累积转化',
    tooltipTitle: '转化率',
    chartType: 6, // 请求趋势图type
    icon: lecturerRefresh,
    rate: true
  }
]);
const statisticsSel = ref(statisticsRadius.value[0].key);
const currentStatistics:Record<string, any> = computed(() => {
  return statisticsRadius.value.find((item) => item.key === statisticsSel.value);
});
function statRadiusClick(item: Record<string, any>) {
  statisticsSel.value = item.key;
  getLecStatisticsTrend();
}
const { initDate, initDtArr } = toolGetCountInitDateRange();

const dateSel = ref({
  fromDt: initDtArr[0],
  toDt: initDtArr[1]
});
const trendDateRange = ref<any[]>(initDate);
const timeChange = (val: any[]) => {
  const { from, to, range } = timeDeal(val);
  trendDateRange.value = range;
  dateSel.value.fromDt = from;
  dateSel.value.toDt = to;
  getLecStatisticsTrend();// 图表刷新
};
const timeDeal = (val: any[]) => {
  let res = {
    to: '',
    from: '',
    range: [] as any[]
  };
  if (val && val.length) {
    const from = dayjs(val[0]).format('YYYYMMDD');
    const to = dayjs(val[1]).format('YYYYMMDD');
    res = {
      from,
      to,
      range: [from, to]
    };
  }
  return res;
};
// 图表逻辑
const chartMap = ref<Record<string, any>>({
  new_users: {
    title: '用户增长趋势',
    infoList: [
      { lab: '所选区间用户增长总数', val: '99999' },
      { lab: '单日最高增长数', val: '99999' },
      { lab: '单日最低增长数', val: '99999' }
    ]
  },
  gmv: {
    title: '成交趋势',
    infoList: [
      { lab: '所选区间成交总数', val: '￥99999' },
      { lab: '单日最高成交值', val: '￥99999' },
      { lab: '单日最低成交值', val: '￥99999' }
    ]
  },
  order: {
    title: '订单趋势',
    infoList: [
      { lab: '所选区间订单总数', val: '99999' },
      { lab: '单日最高订单数', val: '99999' },
      { lab: '单日最低订单数', val: '99999' }
    ]
  },
  atv: {
    title: '客单价趋势',
    infoList: [
      { lab: '最高日均客单价', val: '$99999' },
      { lab: '最低日均客单价', val: '$99999' }
    ]
  },
  change_ratio: {
    title: '转化率趋势',
    infoList: [
      { lab: '所选区间最高转化率', val: '99.22%' },
      { lab: '最低转化率', val: '99.22%' }
    ]
  }
});
const currentChartInfo = computed<Record<string, any>>(() => {
  return chartMap.value[statisticsSel.value];
});
const chartLoading = ref(true);
let xData = ref<any[]>([]);
let yData = ref<any[]>([]);
let minData = ref(0);
let maxData = ref(0);
let totalData = ref(0);
const numFormat = (val:number) => {
  if (currentStatistics.value.rmb) {
    return `￥${Number(val.toFixed(1)) /* .toLocaleString() */}`;
  } else if (currentStatistics.value.rate) {
    return `${formatPercent(val)}%`;
  }
  return val /* .toLocaleString() */;
};
const toolNumFormat = (val:number) => {
  if (currentStatistics.value.rmb) {
    return `￥${Number(val.toFixed(1)) /* .toLocaleString() */}`;
  } else if (currentStatistics.value.rate) {
    return `${val}%`;
  }
  return val /* .toLocaleString() */;
};
const getLecStatisticsTrend = async () => {
  let chartData: any[]= [];
  xData.value = [];
  yData.value = [];
  minData.value = 0;
  maxData.value = 0;
  totalData.value = 0;
  chartLoading.value = true;
  const res = await lecStatisticsTrend({
    channel: currentStat.value.id,
    type: currentStatistics.value.chartType,
    fromDt: dateSel.value.fromDt,
    toDt: dateSel.value.toDt
  });
  const { data, min, max, total } = res.data;
  minData.value = min;
  maxData.value = max;
  totalData.value = total;
  data.forEach((item: {ts:string, value:number}) => {
    let value: any = item.value;
    if (currentStatistics.value.chartType === 6) value = formatPercent(value);
    chartData.push(value);
    xData.value.push(item.ts);
  });
  yData.value = [
    {
      name: '趋势图',
      color: '#307AF2',
      data: chartData
    }
  ];
  if (currentChartInfo.value.infoList.length === 2) {
    currentChartInfo.value.infoList[0].val = numFormat(maxData.value);
    currentChartInfo.value.infoList[1].val = numFormat(minData.value);
  } else {
    currentChartInfo.value.infoList[0].val = numFormat(totalData.value);
    currentChartInfo.value.infoList[1].val = numFormat(maxData.value);
    currentChartInfo.value.infoList[2].val = numFormat(minData.value);
  }
  chartLoading.value = false;
};
const tooltip = (params: any) => {
  // 图例数据
  let itemStr = '';
  params.forEach((item: any) => {
    itemStr += `
    <div style="width:100%;margin-bottom:10px;color: #fff;">${dayjs.unix(item.axisValue).format('MM-DD')}</div>
    <div class="row">
      <div class="sample" style="background: ${item.color}"></div>
      <div class="name">${ currentStatistics.value.tooltipTitle}：</div>
                <div class="value">
                  <div class="value-inner">
                    <span class="number">${toolNumFormat(item.value)}</span>
                  </div>
                </div>
          </div>`;
  });

  const str = `<div class="chart-tooltip line">
    ${itemStr}
  </div>`;

  return str;
};
// 业务逻辑

const statistics = ref<Record<string, any>>({});
const init = () => {
  getLecFollower();
  getLecStatisticsCore();
  getLecStatisticsTrend(); // 图表刷新
};

const dataRefresh = () => {
  getLecStatisticsCore();
  getLecStatisticsTrend(); // 图表刷新
};

const getLecStatisticsCore=async () => {
  if (currentStat.value.id === 0) {
    const res = await lecStatisticsCore({});
    const { data } = res;
    statistics.value = handleTransData(data);
  } else {
    const res = await lecStatisticsCore({
      channel: currentStat.value.id
    });
    const { data } = res;
    statistics.value = handleTransData(data);
  }
};
const handleTransData = (data) => {
  const { is_desensitization } = data;
  const newData = {};
  for (let item in data) {
    /** 如果需要脱敏，累计用户数和今日新增用户除外的字段皆返回 -  */
    newData[item] = is_desensitization ? !['new_users', 'total_users'].includes(item) ? '-' : data[item] : data[item];
  }
  return newData;
};
onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.lecturer-data {
  .flex {
    display: -webkit-box;
    display: flex;
  }

  .inline-flex {
    display: -webkit-inline-box;
    display: inline-flex;
  }

  .flex,
  .inline-flex {
    & > *, & > view, & > image { // 修复flex子元素溢出问题
      min-width: 0;
      min-height: 0;
    }
  }

  .flex-0 {
    flex: 0 0 auto;
  }

  .flex-1 {
    flex: 1 1 auto;
  }

  .cross-center {
    -webkit-box-align: center;
    align-items: center;
  }

  .cross-stretch {
    -webkit-box-align: stretch;
    align-items: stretch;
  }

  .main-between {
    -webkit-box-pack: justify;
    justify-content: space-between;
  }

  .dir-top {
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    flex-direction: column;
  }

  .top-box {
    .statistic-scroll {
      margin-top: 29px - 12px;

      // overflow-x: auto;
      // overflow-y: hidden;
    }

    .statistic {
      white-space: nowrap;
    }

    .item {
      padding: 12px 10px;
      margin: 0 25px;
      cursor: pointer;
    }

    .svg-icon {
      display: block;
      overflow: hidden;
      transform: translateY(1px);

      img {
        display: block;
        width: 16px;
        height: 16px;
        filter: drop-shadow(#86909c -200px 0);
        transform: translateX(200px);
      }
    }

    .name {
      margin-left: 12px;
      font-size: 18px;
      font-weight: 600;
      line-height: 22px;
      color: #86909c;
    }

    .item.active {
      position: relative;

      &::after {
        position: absolute;
        right: 10px;
        bottom: 0;
        left: 10px;
        height: 4px;
        content: '';
        background: #307af2;
        border-radius: 2px;
      }

      .name {
        color: #307af2;
      }

      .svg-icon img {
        filter: drop-shadow(#307af2 -200px 0);
      }
    }
  }

  .content {
    .head {
      .title {
        font-size: 18px;
        font-weight: 500;
        line-height: 22px;
        color: #4e5969;
      }
    }

    .left {
      min-width: 288px;
      max-width: 288px;
      margin-right: 10px;

      .head {
        padding: 33px 35px;
        margin-bottom: 10px;
        background: linear-gradient(94.63deg, #4080ff 0%, #6db9ff 100%);
        border-radius: 4px;

        .title {
          font-size: 16px;
          font-weight: 500;
          line-height: 22px;
          color: #f2f3f5;
        }

        .number {
          font-size: 28px;
          font-weight: 600;
          line-height: 22px;
          color: #f2f3f5;
        }
      }

      .sub {
        padding: 14px 20px;
        background: #fff;
        border-radius: 4px;

        .item {
          padding: 40px 24px;
          margin-bottom: 14px;
          cursor: pointer;
          background: #f7f8fa;
          border-radius: 2px 0 0 2px;

          &:last-child {
            margin-bottom: 0;
          }

          .svg-icon {
            display: block;
            padding: 4px;
            overflow: hidden;
            background-color: #c9cdd4;
            border-radius: 50%;

            img {
              display: block;
              width: 20px;
              height: 20px;
              filter: drop-shadow(#fff -200px 0);
              transform: translateX(200px);
            }
          }

          .title {
            margin-left: 8px;
            font-size: 14px;
            font-weight: 500;
            line-height: 22px;
            color: #4e5969;
          }

          .value {
            font-size: 16px;
            font-weight: 500;
            line-height: 22px;
            color: #4e5969;
          }

          &.active {
            background: #307af2;

            .svg-icon {
              background-color: #fff;

              img {
                filter: drop-shadow(#307af2 -200px 0);
              }
            }

            .title {
              color: #fff;
            }

            .value {
              color: #fff;
            }
          }
        }
      }
    }

    .right {
      position: relative;
      padding: 24px;
      background: #fff;

      .bar {
        padding: 10px 24px;
        margin-top: 26px;
        background: #e8f3ff;
        border-radius: 4px;

        .lab {
          font-size: 12px;
          font-weight: 400;
          line-height: 22px;
          color: #86909c;
        }

        .val {
          margin-right: 30px;
          margin-left: 6px;
          font-size: 16px;
          font-weight: 600;
          line-height: 22px;
          color: #4e5969;

          &:last-child {
            margin-right: 0;
          }
        }
      }

      .chart-wrap {
        margin-top: 25px;
      }
    }
  }
}
</style>
